export const parseJDProductsScript = String.raw`(() => {
  const SNAPSHOT_MAX_LENGTH = 1000;
  const TEXT_NODE = typeof Node !== 'undefined' ? Node.TEXT_NODE : 3;

  const trimText = (value) => (typeof value === 'string' ? value.trim() : '');

  const collectProducts = () => {
    const products = [];
    const productCards = document.querySelectorAll('.plugin_goodsCardWrapper');

    productCards.forEach((card, index) => {
      try {
        const titleElement = card.querySelector('[class*="_text"]');
        const title = trimText(titleElement ? titleElement.textContent : '');

        const priceElement = card.querySelector('[class*="_price"]');
        let price = '';
        if (priceElement) {
          const yenSymbol = trimText(priceElement.querySelector('[class*="_yen"]')?.textContent || '');
          const mainPrice = Array.from(priceElement.childNodes || [])
            .filter((node) => node.nodeType === TEXT_NODE)
            .map((node) => trimText(node.textContent || ''))
            .join('');
          const decimal = trimText(priceElement.querySelector('[class*="_decimal"]')?.textContent || '');
          price = yenSymbol + mainPrice + decimal;
        }

        const sku = card.getAttribute('data-sku') || '';

        const imgElement = card.querySelector('[class*="_img"]');
        let imgUrl = '';
        if (imgElement) {
          imgUrl = imgElement.getAttribute('src') || imgElement.getAttribute('data-src') || '';
          if (imgUrl.startsWith('//')) {
            imgUrl = 'https:' + imgUrl;
          }
        }

        const shopElement = card.querySelector('[class*="_name"] span');
        const shopName = trimText(shopElement ? shopElement.textContent : '');

        const tags = [];
        card.querySelectorAll('[class*="_textTag"] span, [class*="_imgTag"] img').forEach((tag) => {
          const text = trimText(tag.textContent || tag.getAttribute('alt') || '');
          if (text) {
            tags.push(text);
          }
        });

        const volumeElement = card.querySelector('[class*="_goods_volume"]');
        const salesInfo = trimText(volumeElement ? volumeElement.textContent : '');

        const titleContainer = card.querySelector('[class*="_goods_title_container"]');
        let selector = null;
        if (titleContainer) {
          const titleClass = Array.from(titleContainer.classList || []).find((cls) => cls.includes('_goods_title_container'));
          if (titleClass) {
            selector = '.' + titleClass;
          }
        }

        const pointId = card.getAttribute('data-point-id');

        const selectors = {
          byTitleContainer: selector,
          bySku: sku ? '[data-sku="' + sku + '"]' : null,
          byPointId: pointId ? '[data-point-id="' + pointId + '"]' : null,
          generic: '[class*="_goods_title_container"]'
        };

        const preferredSelector = selectors.byTitleContainer || selectors.bySku || selectors.byPointId || selectors.generic;

        products.push({
          index: index + 1,
          title,
          price,
          sku,
          selector: preferredSelector || '',
          selectors,
          imgUrl,
          shopName,
          tags,
          salesInfo
        });
      } catch (error) {
        console.error('[parse-jd-products] 解析商品失败:', error);
      }
    });

    return products;
  };

  const productItems = (() => {
    try {
      return collectProducts();
    } catch (error) {
      console.error('[parse-jd-products] collectProducts 失败:', error);
      return [];
    }
  })();

  const domSnapshots = productItems
    .map((item, idx) => {
      const selectors = item.selectors || {};
      const candidates = [item.selector, selectors.byTitleContainer, selectors.bySku, selectors.byPointId, selectors.generic]
        .filter(Boolean);

      let target = null;
      for (const sel of candidates) {
        const node = sel ? document.querySelector(sel) : null;
        if (node) {
          target = node;
          break;
        }
      }

      if (!target) {
        return null;
      }

      const snapshotSelector = candidates.find(Boolean) || '';

      return {
        index: item.index ?? idx + 1,
        selector: snapshotSelector,
        html: (target.outerHTML || '').slice(0, SNAPSHOT_MAX_LENGTH)
      };
    })
    .filter(Boolean);

  return JSON.stringify({ productItems, domSnapshots });
})()`;

export default parseJDProductsScript;
